<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0px;
        top: 0px;
      }

      .box2 {
        width: 100px;
        height: 100px;
        background: blue;
        position: absolute;
        left: 300px;
        top: 0px;
      }
    </style>
  </head>

  <body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
      // 红色方块拖动
      var box1Ele = document.querySelector(".box1");
      var box2Ele = document.querySelector(".box2");

      box1Ele.onmousedown = function (e) {
        var e = e || window.e;
        this.style.zIndex = 10;
        var x = e.clientX - box1Ele.offsetLeft;
        var y = e.clientY - box1Ele.offsetTop;
        box1Ele.onmousemove = function (event) {
          var event = event || window.event;
          var xx = event.clientX - x;
          var yy = event.clientY - y; //计算移动之后盒子偏移量
          this.style.left = `${xx}px`;
          this.style.top = `${yy}px`;
          if (
            Math.abs(box2Ele.offsetLeft - box1Ele.offsetLeft) <
              box1Ele.offsetWidth &&
            Math.abs(box2Ele.offsetTop - box1Ele.offsetTop) <
              box1Ele.offsetHeight
          ) {
            console.log("碰撞ing");
          }
        };
      };
      document.onmouseup = function () {
        box1Ele.onmousemove = "";
      };
    </script>
  </body>
</html>
